package com.ljs.tranctionldemo.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;

import java.io.Serializable;

@Data
@ToString
//用来转换json的格式的类
public class Result<R> implements Serializable {

    private boolean success;
    private int code;
    private String msg;
    private R data;
    public static final Integer defErrCode = -1;

    public static <R> Result<R> ofSuccess(R data) {
        return new Result<R>()
                .setSuccess(true)
                .setCode(SystemEnum.SUCCESS.getCode())
                .setMsg(SystemEnum.SUCCESS.getMsg())
                .setData(data);
    }

    public static <R> Result<R> ofSuccessMsg(String msg) {
        return new Result<R>()
                .setSuccess(true)
                .setMsg(msg);
    }

    public static <R> Result<R> ofFailMsg(String msg){
        return new Result<R>()
                .setSuccess(false)
                .setCode(defErrCode)
                .setMsg(msg);
    }

    /**
     * 错误枚举响应
     * @param baseEnum
     * @param <R>
     * @return
     */
    public static <R> Result<R> ofFail(BaseEnum baseEnum) {
        Result<R> result = new Result<>();
        result.setSuccess(false);
        result.setCode(baseEnum.getCode());
        result.setMsg(baseEnum.getMsg());
        return result;
    }

    /**
     * 指定错误响应
     * @param code 错误编码
     * @param msg 错误信息
     * @param <R>
     * @return
     */
    public static <R> Result<R> ofFail(Integer code, String msg) {
        Result<R> result = new Result<>();
        result.setSuccess(false);
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public Result<R> setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public Result<R> setCode(int code) {
        this.code = code;
        return this;
    }

    public Result<R> setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result<R> setData(R data) {
        this.data = data;
        return this;
    }
}
